package com.wing.productionPlan.controller.app;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.utils.JsonResult;
import com.wing.productionPlan.model.response.SimpleWorkOrderProcessVO;
import com.wing.web.excel.DownExcelUtil;
import com.wing.web.utils.JwtUtils;
import com.wing.web.utils.LocaleMessage;
import com.wing.common.utils.PageResult;
import com.wing.productionPlan.model.entity.SimpleWorkOrder;
import com.wing.productionPlan.model.response.SimpleWorkOrderVO;
import com.wing.productionPlan.service.SimpleWorkOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.wing.productionPlan.model.request.SimpleWorkOrderForm;
import org.springframework.validation.annotation.Validated;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 *
 * @author
 */
@Slf4j
@Validated
@Api(value = "App-简版工单表管理", tags = "简版工单表管理")
@RestController("appSimpleWorkOrderController")
@RequestMapping("productionPlan/app/simpleWorkOrder")
public class SimpleWorkOrderController {

    @Autowired
    private SimpleWorkOrderService simpleWorkOrderService;
    @Autowired
    private LocaleMessage localeMessage;

    @ApiOperation(value = "查询所有工单", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<SimpleWorkOrderVO> list(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "desc") String order
            ,String code
            ,String deviceCode
            ,Long processId
            ,String skuCode
            ,@RequestParam(defaultValue = "false")Boolean orderQueryFlag
    ) {
        Page<SimpleWorkOrderVO> pg = new Page<>(page, limit);
        Map<String, Object> params = new HashMap<>();
        params.put("orderQueryFlag", orderQueryFlag);

        //排序
        /*if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            params.put("sort", sort);
            params.put("order", order);
        }*/
        if(StringUtils.isNotBlank(code)){
            params.put("code", code);
        }
        if(StringUtils.isNotBlank(deviceCode)){
            params.put("deviceCode", deviceCode);
        }
        if(processId != null){
            params.put("processId", processId);
        }

        //查询开工的
        params.put("status",2);
        params.put("enterpriseCode",JwtUtils.getEnterpriseCode());
        //如果工单查询标记是关闭的，且查询的编码为空，则直接返回空
        if(orderQueryFlag && StringUtils.isBlank(code)){
            return new PageResult<>(null, 0);
        }else{
            Page<SimpleWorkOrderVO> list = simpleWorkOrderService.pageList4app(pg, params);
            return new PageResult<>(list.getRecords(), list.getTotal());
        }
    }

    @GetMapping("/{id}")
    public JsonResult detail(@PathVariable("id") Long simpleWorkOrderId) {
        SimpleWorkOrderVO simpleWorkOrderVO = simpleWorkOrderService.get4appById(simpleWorkOrderId);
        if (simpleWorkOrderVO == null) {
            return JsonResult.fail(localeMessage.getMessage("common.fail"));
        }
        return JsonResult.success(localeMessage.getMessage("common.success"), simpleWorkOrderVO);
    }
    @ApiOperation(value = "添加工单", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "simpleWorkOrderForm", value = "插入的数据", required = true, dataType = "list", paramType = "path")
    })
    @PostMapping("/submitWorkOrder")
    public JsonResult add(@RequestBody SimpleWorkOrderForm simpleWorkOrderForm) {
        try {
            simpleWorkOrderForm.setStatus(SimpleWorkOrder.Status.start);
            simpleWorkOrderService.addNewSimpleWorkOrder(simpleWorkOrderForm);
            return JsonResult.success("操作成功");
        }catch (Exception e){
            log.error("简版工单添加接口异常，原因是：{} ", e.getMessage(), e);
            return JsonResult.fail("操作失败:" + e.getMessage());
        }
    }
    @ApiOperation(value = "完结", notes = "修改")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "status", value = "1", required = true, dataType = "int", paramType = "path")
    })
    @PutMapping("/update")
    public JsonResult update(@Validated(SimpleWorkOrderForm.Update.class) SimpleWorkOrderForm simpleWorkOrderForm) {
        SimpleWorkOrder simpleWorkOrder = simpleWorkOrderService.getById(simpleWorkOrderForm.getId());
        if(simpleWorkOrder == null){
            return JsonResult.fail("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(SimpleWorkOrder.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(simpleWorkOrderForm, simpleWorkOrder, copyOptions);
        if (simpleWorkOrderService.updateById(simpleWorkOrder)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }

    @ApiOperation(value = "查询工单详情", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "工单id", required = true, dataType = "list", paramType = "path")
    })
    @GetMapping("/getSimpleWorkOrderVODetails")
    public JsonResult<SimpleWorkOrderVO> getSimpleWorkOrderVODetails(Long id){
        SimpleWorkOrderVO workOrderVO = simpleWorkOrderService.getSimpleWorkOrderVODetails(id);
        return JsonResult.success(workOrderVO);
    }

    @ApiOperation(value = "查询工单详情工序下的设备和物料", notes = "查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "processId", value = "工序id", required = true, dataType = "list", paramType = "path")
            ,@ApiImplicitParam(name = "workOrderId", value = "工单id", required = true, dataType = "list", paramType = "path")
    })
    @GetMapping("/getWorkOrderDeviceAndMaterial")
    public JsonResult<SimpleWorkOrderProcessVO> getWorkOrderDeviceAndMaterial(Long processId,Long workOrderId){
        SimpleWorkOrderProcessVO simpleWorkOrderProcessVO = simpleWorkOrderService.getWorkOrderDeviceAndMaterial(processId,workOrderId);
        return JsonResult.success(simpleWorkOrderProcessVO);
    }
    @ApiOperation(value = "查询历史工单的物料已经计算预估数量", notes = "修改")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "skuCode", value = "生产产品编号", required = true, dataType = "string", paramType = "path")
            ,@ApiImplicitParam(name = "productionQuantity", value = "生产数量", required = true, dataType = "Int", paramType = "path")
    })
    @GetMapping("/getMaterialForecastData")
    public JsonResult<List<SimpleWorkOrderProcessVO>> getMaterialForecastData(@RequestParam(value = "skuCode")String skuCode
            , @RequestParam(value = "productionQuantity")Integer productionQuantity
    ){
        return simpleWorkOrderService.getMaterialForecastData(skuCode,productionQuantity);
    }
}
